package user

import (
	"context"
	"strconv"

	"mall/common/jwt"
	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetUserInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserInfoLogic {
	return &GetUserInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetUserInfoLogic) GetUserInfo() (resp *types.UserBaseInfoResp, err error) {
	// var userId string = l.ctx.Value("userId").(string)
	userId := jwt.GetBackendUserId(l.ctx)
	if userId == 0 {
		return nil, errorx.NewApiUnauthorizedError("login.requireLogin")
	}

	data, err := l.svcCtx.BackendRpc.GetUserById(l.ctx, &backendclient.UserIdReq{
		Id:        userId,
		WithRoles: pointy.GetPointer(uint32(1)),
	})
	if err != nil {
		return
	}

	var name *string
	if data.Nickname != nil && len(*data.Nickname) > 0 {
		name = data.Nickname
	} else if data.Username != nil && len(*data.Username) > 0 {
		name = data.Username
	}

	return &types.UserBaseInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: types.UserBaseInfo{
			Id:          data.Id,
			UUID:        pointy.GetPointer(strconv.FormatInt(int64(*data.Id), 10)),
			Username:    data.Username,
			Nickname:    data.Nickname,
			Avatar:      data.Avatar,
			HomePath:    data.HomePath,
			Description: data.Description,
			Name:        name,
			Access:      pointy.GetPointer("admin"),
		},
	}, nil
}
